package message

import (
	"api/common"
	"api/pb/group"
	"api/pb/message"
	"context"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateMessageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateMessageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateMessageLogic {
	return &CreateMessageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// CreateMessage 发送消息
func (l *CreateMessageLogic) CreateMessage(req *types.MessageInfo) (resp *types.Empty, err error) {
	// 1. 获取用户标识
	userID, err := common.GetUserIDFromCtx(l.ctx)
	if err != nil {
		return nil, err
	}
	// 2. 生成消息ID
	messageID, err := common.GenerateSnowflakeID()
	if err != nil {
		return nil, err
	}

	// 3. 使用异步创建消息
	data := "zhangSan"
	if err := l.svcCtx.KqPusherClient.Push(l.ctx, data); err != nil {
		logx.Errorf("KqPusherClient Push Error , err :%v", err)
	}

	// 3. 校验接收人
	var receiverIds []int64
	switch req.ReceiverType {
	case common.ReceiverTypeSingle:
		receiverIds = append(receiverIds, req.ReceiverID)
	case common.ReceiverTypeGroup:
		groupMembers, err := l.svcCtx.GroupRPC.GetMemberList(l.ctx, &group.MemberListRequest{
			GroupId: req.ReceiverID, Offset: 0, Limit: 1000,
		})
		if err != nil {
			return nil, err
		}
		for _, member := range groupMembers.Data {
			if member.UserId == userID {
				continue
			}
			receiverIds = append(receiverIds, member.UserId)
		}
	}

	// 4. 创建消息
	_, err = l.svcCtx.MessageRPC.CreateMessage(l.ctx, &message.MessageInfo{
		Id: messageID, SenderId: userID, ReceiverType: req.ReceiverType,
		ReceiverId: req.ReceiverID, ReceiverIds: receiverIds,
		ContentType: req.ContentType, Content: req.Content,
		FileName: req.FileName, FileSize: req.FileSize,
	})
	if err != nil {
		return nil, err
	}
	return &types.Empty{}, nil
}
